package com.calendar.api.service.impl;

import com.calendar.api.model.Category;
import com.calendar.api.model.User;
import com.calendar.api.model.dto.CategoryDTO;
import com.calendar.api.repository.CategoryRepository;
import com.calendar.api.repository.UserRepository;
import com.calendar.api.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityNotFoundException;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    private final CategoryRepository categoryRepository;
    private final UserRepository userRepository;

    @Autowired
    public CategoryServiceImpl(CategoryRepository categoryRepository, UserRepository userRepository) {
        this.categoryRepository = categoryRepository;
        this.userRepository = userRepository;
    }

    @Override
    public List<Category> getAllCategories(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在: " + userId));
        return categoryRepository.findByUser(user);
    }

    @Override
    public Category getCategory(Long id, Long userId) {
        Category category = categoryRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("分类不存在: " + id));
        
        // 验证分类所属用户
        if (!category.getUser().getId().equals(userId)) {
            throw new EntityNotFoundException("分类不存在: " + id);
        }
        
        return category;
    }

    @Override
    public Category createCategory(CategoryDTO categoryDTO, Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在: " + userId));
        
        Category category = new Category();
        category.setName(categoryDTO.getName());
        category.setUser(user);
        return categoryRepository.save(category);
    }

    @Override
    public Category updateCategory(Long id, CategoryDTO categoryDTO, Long userId) {
        Category existingCategory = getCategory(id, userId);
        existingCategory.setName(categoryDTO.getName());
        return categoryRepository.save(existingCategory);
    }

    @Override
    public void deleteCategory(Long id, Long userId) {
        Category category = getCategory(id, userId);
        categoryRepository.delete(category);
    }
} 